import { Response } from 'express'
import { v4 as uuid } from 'uuid'
import dayjs from "dayjs";
import {
    fileAddDao,
    fileDelDao,
    fileItemAddDao,
    fileListDao, filePathListDao,
    fileUserAddDao,
    fileUserDelDao,
    IFile
} from '../dao/fileDao'
import {IPromiseCommonResponse, ISqlInsert, tokenParams} from "../../global";
import {parseToken} from "../utils/jwt";
import {commonResponse} from "../utils/commonResponse";
import FileMethod from "../utils/fileMethod";

// 添加文件夹
export const fileAddService = async (res: Response, fileName: string, type: string, token: string, state: string, parentFileUID: string) => {
    await commonResponse<IPromiseCommonResponse<{ msg: string }>, { msg: string }>(res, async () => {
        const fileUID = uuid()
        await fileAddDao([fileUID, fileName, dayjs().format('YYYY-MM-DD HH:mm:ss'), type, parentFileUID])
        const userFileUID = uuid()
        const params = parseToken(token)
        await fileUserAddDao([userFileUID, (params as tokenParams).userUID, fileUID, state])
        return Promise.resolve({ code: 200, data: { msg: '成功' }})
    })
}

// 获取文件列表
export const fileListService = async (res: Response, token: string, fileUID: string) => {
    await commonResponse<IPromiseCommonResponse<Array<IFile>>, Array<IFile>>(res ,  async () => {
        const params = parseToken(token)
        const list = await fileListDao([(params as tokenParams).userUID, fileUID])
        const data:  Array<{ key: string } & IFile> = []
        for (let i = 0; i < list.length; i++) {
            data.push({ key: list[i].fileUID, ...list[i] })
        }
        return Promise.resolve({ code: 200, data })
    })
}

// 删除文件
export const fileDelService = async (res: Response, fileUIDList: Array<string>) => {
    await commonResponse<IPromiseCommonResponse<{ msg: string }>, { msg: string }>(res, async () => {
        const pathList: Array<{ path: string }> = await filePathListDao(fileUIDList)
        for (let i = 0; i < pathList.length; i++) {
            await FileMethod.fileDel(pathList[i].path)
        }
        await fileUserDelDao(fileUIDList)
        await fileDelDao(fileUIDList)
        return Promise.resolve({ code: 200, data: { msg: '成功' } })
    })
}

// 上传文件`fileUID`, `fileName`, `time`, `type`, `parentFileUID`, `size`, `path`
export const fileItemAddService = async (res: Response, parentFileUID: string, fileName: string, type: string, size: number, path: string, token: string, state: string) => {
    await commonResponse<IPromiseCommonResponse<{ msg: string }>, { msg: string }>(res, async () => {
        const fileUID = uuid()
        await fileItemAddDao([fileUID, fileName, dayjs().format('YYYY-MM-DD HH:mm:ss'), type, parentFileUID, size, path])
        const userFileUID = uuid()
        const params = parseToken(token)
        await fileUserAddDao([userFileUID, (params as tokenParams).userUID, fileUID, state])
        return Promise.resolve({ code: 200, data: { msg: '成功' } })
    })
}
